<template>
  <!--新增/编辑定期检查-->
  <vx-popup :title="dialogTitle" width="970px" @close="cancelSubmit" :active.sync="dialogVisible"
    @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <div >
        <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称 :" prop="name" label-width="95px">
              <el-input v-model="ruleForm.name" placeholder="请输入名称" size="small" style="width:100%" clearable :disabled="isDisable"  maxlength="20">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属桥梁 :" prop="bridgeName" label-width="95px">
              <el-select v-model="ruleForm.bridgeName" placeholder="请选择所属桥梁" size="small" style="width:100%" clearable @change="changeBridge" :disabled="isDisable">
                   <el-option v-for="(item , index) in bridgeOptions" :key="item.id" :label="item.name" :value="index">
            </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级 :" prop="level" label-width="95px">
              <el-select v-model="ruleForm.level" placeholder="请选择等级" size="small" style="width:100%" clearable :disabled="isDisable">
                   <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="BCI评分 :" prop="score" label-width="95px">
              <el-input v-model="ruleForm.score" placeholder="请输入BCI评分" size="small" style="width:100%" clearable :disabled="isDisable">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <el-form-item label="附件 :" prop="fileDtoList" label-width="95px">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeImgUpload"
                :on-success="handleSuccess"
                multiple
                :file-list="ruleForm.fileDtoList">
                <el-button size="medium " icon="el-icon-plus" type="text" style="font-size:30px" :disabled="isDisable"></el-button>
                <div slot="tip" class="el-upload__tip" style="display:inline-block;margin-left:20px;">支持word、excel、ppt、pdf、图片（jpg、png、bmp格式）、文本文件，最多9个附件，单个附件最大200M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <el-form-item label="检测结论 :" prop="conclusion" label-width="95px">
              <el-input v-model="ruleForm.conclusion" placeholder="请输入检测结论" size="small" style="width:100%" clearable type="textarea" maxlength="1000" show-word-limit rows="6" :disabled="isDisable"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <el-form-item label="技术建议 :" prop="advice" label-width="95px">
              <el-input v-model="ruleForm.advice" placeholder="请输入技术建议" size="small" style="width:100%" clearable type="textarea" maxlength="1000" show-word-limit rows="6" :disabled="isDisable"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </vx-popup>

</template>

<script>
  import base from "@/api/base";
  export default {
    props: {
      createType: {
        type: Number,
        required: true,
        default: 4
      }
    },
    data() {
      var validateScore = (rule, value, callback) => {
        let reg = /^(100)$|^((\d|[1-9]\d)(\.\d{1,2})?)$/
        if(this.ruleForm.score === '') {
          callback(new Error('请输入BCI评分'));
        } else if (reg.test(this.ruleForm.score) !== true) {
          callback(new Error('请输入100以内正数，最多小数点后2位'));
        } else {
          callback();
        }
      };
      return {
        isDisable: false,
        uploadUrl: base.UPLOADURL,
        isResouceShow: 0,
        dialogTitle: '新增定期检查',
        dialogVisible: false,
        editId: '',
        bridgeOptions: [],
        personOptions: [],
        deasePosOptions: {},
        fileList:[],
        ruleForm: {
          name: '',
          fileDtoList:[],
          bridgeId:'',
          bridgeName:'',
          maintenanceType:'',
          level:'',
          score:'',
          conclusion:'',
          advice:''
        },
        rules: {
          name: [{
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }],
          score: [{
            required: true,
            validator: validateScore,
            trigger: "blur"
          }],
          conclusion: [{
            required: true,
            message: "请输入检测结论",
            trigger: "blur"
          }],
          advice: [{
            required: true,
            message: "请输入技术建议",
            trigger: "blur"
          }],
          bridgeName: [{
            required: true,
            message: "请选择所属桥梁",
            trigger: ['change','blur']
          }],
          level: [{
            required: true,
            message: "请选择等级",
            trigger: "change"
          }]
        },
        levelList:[],
        level:[
            {
                value:'0',
                label:'合格'
            },
             {
                value:'1',
                label:'不合格'
            }
        ],
        otherLevel:[
             {
                value:'0',
                label:'A级'
            },
             {
                value:'1',
                label:'B级'
            },
             {
                value:'2',
                label:'C级'
            },
             {
                value:'3',
                label:'D级'
            },
             {
                value:'4',
                label:'E级'
            }
        ]
      };
    },
    created() {
      this.queryBridgeList()
    },
    methods: {
      changeBridge(val){
          this.ruleForm.maintenanceType = ''
          this.ruleForm.level = ''
          this.levelList = []
          this.ruleForm.bridgeId = this.bridgeOptions[val].id
          this.ruleForm.bridgeName = this.bridgeOptions[val].name
          this.ruleForm.maintenanceType = this.bridgeOptions[val].maintenanceType
          if(this.ruleForm.maintenanceType === '0') {
              this.levelList = this.level
          } else {
              this.levelList = this.otherLevel
          }
      },
      handleSuccess(res, file, fileList){
          if(res.code === 200) {
            let _id = res.data.successFiles[0].id;
            let _ext = res.data.successFiles[0].fileSuffix;
            let _filePath = res.data.successFiles[0].filePath;
            let _name = res.data.successFiles[0].originalFileName;
            this.ruleForm.fileDtoList.push({
              picId: _id,
              type: _ext,
              filePath: _filePath,
              name: `${_name}.${_ext}`
            })
          }
          
      },
       handleRemove(file, fileList) {
        this.$set(this.ruleForm, 'fileDtoList', fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      beforeImgUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 200
            if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 200MB!')
            return false
            }
        },
      add(val) {
        this.emptyForm();
        this.editId = null;
        this.dialogTitle = '新增定期检查';
        this.dialogVisible = true;
        this.isDisable = false
      },
      edit(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogTitle = '编辑定期检查';
        this.dialogVisible = true;
        this.isDisable = false
        this.editId = val;
        this.queryById(val)
      },
      detail(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogTitle = '查看定期检查';
        this.dialogVisible = true;
        this.editId = val;
        this.isDisable = true
        this.queryById(val)
      },
      queryById(val) {
        this.$api.insp.getRegular(val).then(response => {
          const _data = response.data.data;
          let list = []
          if(_data.fileList !== null && _data.fileList.length > 0) {
              _data.fileList.map(v => {
                  let obj = {}
                  obj.picId =  v.picId,
                  obj.type = v.type,
                  obj.filePath = v.filePath,
                  obj.name = v.name
                  list.push(obj)
              })
          }
          _data.fileDtoList = list
          this.ruleForm = _data;
        });
      },
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          name: '',
          fileDtoList:[],
          bridgeId:'',
          bridgeName:'',
          maintenanceType:'',
          level:'',
          score:'',
          conclusion:'',
          advice:''
        }
        this.ruleForm = emptyObj;
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then(response => {
          if (response.data.success) {
            this.bridgeOptions = response.data.data[0];
          }
        });
      },
      handleSubmit() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
          let _params = {
            userId: _userInfo['userid'] || '',
            userName: _userInfo['realname'] || '',
            ...this.ruleForm
          };

          if (this.editId) {
            _params.id = this.editId;
          }
          if (this.editId) {
            this.$api.insp.updateRagular(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '修改成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.$emit("closeAddInspTask");
              }
            });
          } else {
            this.$api.insp.saveRegular(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.$emit("closeAddInspTask");
              }
            });
          }
        });
      },
      cancelSubmit() {
        this.dialogVisible = false;
      }
    }
  }

</script>
<style >
  .el-message-box__wrapper{
    z-index:51003 !important;
  }
</style>
<style lang="scss" scoped>
  @import '@/assets/scss/baseColor.scss';
  @import '../insp.scss';

</style>
